﻿using System.IO;
using WP7.Extensions.Helpers;

namespace WP7.Extensions.Extensions
{
    public static class StreamExtensions
    {
        /// <summary>
        /// Reads all text from stream
        /// </summary>
        /// <param name="stream">Stream to read</param>
        /// <returns>Returns string from stream</returns>
        public static string ReadAllText(this Stream stream)
        {
            using (var reader = new StreamReader(stream))
            {
                return reader.ReadToEnd();
            }
        }

        /// <summary>
        /// Returns byte array from stream
        /// </summary>
        /// <param name="stream">Your stream</param>
        /// <returns>Bytes from stream</returns>
        public static byte[] ToByteArray(this Stream stream)
        {
            var outStream = new MemoryStream();
            StreamHelper.CopyStream(stream, outStream, true);
            return outStream.ToArray();
        }

        /// <summary>
        /// Compares each byte in streams 
        /// </summary>
        /// <param name="originalStream">Your stream</param>
        /// <param name="streamToCompareWith">Stream to compare</param>
        /// <returns>Returns true if all bytes are equal</returns>
        public static bool EqualsStream(this Stream originalStream, Stream streamToCompareWith)
        {
            return originalStream.EqualsStream(streamToCompareWith, System.Math.Max(originalStream.Length, streamToCompareWith.Length));
        }

        /// <summary>
        /// Compares each byte in streams 
        /// </summary>
        /// <param name="originalStream">Your stream</param>
        /// <param name="streamToCompareWith">Stream to compare</param>
        /// <param name="readLength">How long to compare stream</param>
        /// <returns>Returns true if all bytes are equal</returns>
        public static bool EqualsStream(this Stream originalStream, Stream streamToCompareWith, long readLength)
        {
            originalStream.Position = 0;
            streamToCompareWith.Position = 0;

            for (var i = 0; i < readLength; i++)
            {
                if (originalStream.ReadByte() != streamToCompareWith.ReadByte())
                    return false;
            }

            return true;
        }


    }
}
